package com.hua.lease.common.utils;

import com.hua.lease.common.exception.LeaseException;
import com.hua.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {

	private static long tokenExpiration = 60 * 60 * 1000L;  //一小时

	private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes());

	public static String createToken(Long userId, String username) {
		String jwt = Jwts.builder().
				setSubject("LOGIN_USER").
				setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)).
				claim("userId", userId).
				claim("username", username).
				signWith(tokenSignKey).
				compact();
		return jwt;
	}

	public static Claims parseToken(String token){

		if (token == null){
			throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
		}

		try {
			JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(tokenSignKey).build();
			Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token);
			return claimsJws.getBody();
		} catch (ExpiredJwtException e) {
			throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
		} catch (JwtException e) {
			throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
		}
	}

	public static void main(String[] args) {
		String token = JwtUtil.createToken(1L, "13888888888");
		System.out.println(token);
	}
}
